<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace app\adminapi\services\setting;

use app\adminapi\validate\setting\SystemAdminValidate;
use app\dao\setting\SystemAdminDao;
use app\dao\setting\SystemDeptDao;
use app\dao\setting\SystemRoleDao;
use Exception;
use kitego\utils\SnowflakeUtil;
use think\db\exception\DbException;

class SystemAdminService
{
    private SystemAdminDao $dao;

    public function __construct(SystemAdminDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 申请管理员
     * @param array $param = ['account' => '', 'password' => '', 'password2' => '', 'agree' => 0, 'realName' => '', 'phone' => '', 'email' => '']
     */
    public function applySystemAdmin(array $param)
    {
        try {
            Validate(SystemAdminValidate::class)->scene('applySystemAdmin')->check($param);

            // 查账号
            $systemAdminModel = $this->dao->getSystemAdminByAccount($param['account']);
            if ($systemAdminModel || $param['password'] != $param['password2'] || !$param['agree']) {
                throw new Exception('账号已存在|二次密码错误|需同意协议');
            }

            // 入库
            $this->dao->save([
                'uuid' => SnowflakeUtil::makeSnowflakeId(),
                'account' => $param['account'],
                'password' => password_hash($param['password'], PASSWORD_BCRYPT),
                'nickname' => '管理员',
                'avatar' => '/static/img/admin/admin_avatar.png',
                'real_name' => $param['realName'],
                'phone' => $param['phone'],
                'email' => $param['email'],
                'status' => 3, // 管理员状态 1:有效 2:禁用 3:待审核
                'delete_flag' => 1,
                'create_time' => now()
            ]);

            return success();
        } catch (Exception $e) {
            return fail($e->getMessage());
        }
    }

    /**
     * 管理员列表
     * @param array $param
     * @throws DbException
     */
    public function listSystemAdmin(array $param = [
        'name' => '', 'groupId' => 0, 'page' => 1, 'pageSize' => 10, 'prop' => '', 'order' => 'ascending', 'filterRole' => 0
    ])
    {
        Validate(SystemAdminValidate::class)->scene('listSystemAdmin')->check($param);

        // 员工列表
        $where[] = ['delete_flag', '=', 0];

        // 关键词模糊搜索
        $whereOr = [];
        if (isset($param['name'])) {
            $param['name'] = trim($param['name']);
            $whereOr = [
                ['account', 'like', '%' . $param['name'] . '%'],
                ['real_name', 'like', '%' . $param['name'] . '%'],
                ['nickname', 'like', '%' . $param['name'] . '%'],
                ['phone', 'like', '%' . $param['name'] . '%'],
                ['email', 'like', '%' . $param['name'] . '%'],
                ['id', 'like', '%' . $param['name'] . '%']
            ];
        }

        // 所属部门
        if (!empty($param['groupId'])) {
            $where[] = ['dept', '=', $param['groupId']];
        }

        // 所属角色
        if (!empty($param['filterRole'])) {
            $where[] = ['role_id', 'find in set', $param['filterRole']];
        }

        // 表头字段排序
        $order = [];
        if (!empty($param['prop']) && !empty($param['order'])) {
            $order['prop'] = camel_to_snake($param['prop']);
            $order['order'] = $param['order'];
        }

        $adminList = $this->dao->listSystemAdmin($where, $whereOr, $order, $param['page'], $param['pageSize']);

        // 角色名称组
        $roleWhere[] = ['delete_flag', '=', 0];
        $roleList = app()->make(SystemRoleDao::class)->getColumn($roleWhere, 'label', 'id');

        // 部门名称数组
        $deptWhere[] = ['delete_flag', '=', 0];
        $deptList = app()->make(SystemDeptDao::class)->getColumn($deptWhere, 'label', 'id');

        foreach ($adminList['data'] as &$v) {
            $v['avatar'] = empty($v['gitee_id']) ? request()->domain() . $v['avatar'] : $v['avatar'];
            $v['deptLabel'] = $deptList[$v['dept']] ?? '';

            // 角色组
            $v['roleGroup'] = [];
            if (!empty($v['role_id'])) {
                $roleIds = explode(',', $v['role_id']);
                $v['role_id'] = [];
                foreach ($roleIds as $vr) {
                    $v['roleGroup'][] = $roleList[$vr] ?? '暂未分配';
                    $v['role_id'][] = (int)$vr;
                }
            }
            $v['roleGroup'] = !empty($v['roleGroup']) ? implode(',', $v['roleGroup']) : '暂未分配';

            unset($v['password']);
        }

        return success($adminList);
    }

    /**
     * 编辑员工
     */
    public function editSystemAdmin(array $params = [
        'id' => 0, 'account' => '', 'avatar' => '', 'dept' => '', 'email' => '', 'nickname' => '', 'phone' => '',
        'realName' => '', 'roleId' => [], 'sort' => 0, 'deleteFlag' => 0, 'status' => 1,
    ])
    {
        Validate(SystemAdminValidate::class)->scene('editSystemAdmin')->check($params);

        if (isset($params['id']) && $params['id'] == 1) {
            if ($params['deleteFlag'] == 1) {
                exception('超管禁止删除');
            }
            if ($params['status'] != 1) {
                exception('超管禁止禁用');
            }
        }

        // 员工数据
        $updateData = [
            'account' => $params['account'],
            'avatar' => $params['avatar'],
            'dept' => $params['dept'],
            'email' => $params['email'],
            'nickname' => $params['nickname'],
            'phone' => $params['phone'],
            'real_name' => $params['realName'],
            'role_id' => implode(',', $params['roleId']),
            'sort' => $params['sort'],
            'delete_flag' => $params['deleteFlag'],
            'status' => $params['status'],
        ];

        // 修改密码
        if (
            isset($params['password']) &&
            isset($params['password2']) &&
            $params['password'] == $params['password2']
        ) {
            $updateData['password'] = password_hash($params['password'], PASSWORD_BCRYPT);
        }

        if (!empty($params['deleteFlag'])) {
            $updateData['delete_time'] = now();
        }

        if (!empty($params['id'])) {
            $updateData['update_time'] = now();
            $id = $this->dao->update($params['id'], $updateData, 'id')->account;
        } else {
            $updateData['create_time'] = now();
            $id = $this->dao->save($updateData)->id;
        }

        return success(['id' => $id]);
    }

    /**
     * 批量删除员工
     * @param array $param
     * @throws DbException
     * @throws Exception
     */
    public function batchDelSystemAdmin(array $param = ['ids' => []])
    {
        Validate(SystemAdminValidate::class)->scene('batchDelSystemAdmin')->check($param);

        if (in_array(1, $param['ids'])) {
            exception('超管禁止删除');
        }

        $where[] = ['id', 'in', $param['ids']];
        $this->dao->update($where, [
            'delete_flag' => 1,
            'delete_time' => now()
        ]);

        return success();
    }
}